#include "wx/wxprec.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif


#include "imysql_front.h"


IMPLEMENT_CLASS( iMySQL_Front, wxFrame )


BEGIN_EVENT_TABLE( iMySQL_Front, wxFrame )

    EVT_SIZE( iMySQL_Front::OnSize )

    EVT_MENU( ID_LOAD_RESULT, iMySQL_Front::OnLoadResult )

//    EVT_MENU( ID_TB_RUN, iMySQL_Front::OnTbRunClick )

//    EVT_MENU( ID_TB_RUN_LINE, iMySQL_Front::OnTbRunLineClick )
    
    EVT_CHOICE( ID_TB_FONT_ENCODING, iMySQL_Front::OnTbChangeFontEncodingClick) 
    
    EVT_TREE_ITEM_ACTIVATED(ID_TREECTRL, iMySQL_Front::OnTreectrlActivated)

    EVT_AUINOTEBOOK_ALLOW_DND(wxID_ANY, iMySQL_Front::OnAllowNotebookDnD)

	EVT_MENU_RANGE(ID_MENUITEM_START,ID_MENUITEM_END,iMySQL_Front::OnMenuClick)

	EVT_MENU_RANGE(ID_TOOLBAR_ID_START,ID_TOOLBAR_ID_END,iMySQL_Front::OnTbClick)

	EVT_TREE_BEGIN_DRAG(ID_TREECTRL, iMySQL_Front::OnBeginDrag)

	EVT_TREE_END_DRAG(ID_TREECTRL, iMySQL_Front::OnEndDrag)

	EVT_TREE_ITEM_MENU( ID_TREECTRL,iMySQL_Front::OnMouseRightClickTreeCtrl )

    EVT_CHOICE( ID_TB_CURRENT_DB, iMySQL_Front::OnDbListChanged )

	EVT_CLOSE( iMySQL_Front::OnCloseButtonClick ) 

	EVT_MENU_RANGE(DB_CONTEXT_MENU_START,DB_CONTEXT_MENU_END, iMySQL_Front::OnDbMenuContextClick )

	EVT_AUINOTEBOOK_PAGE_CHANGED(ID_EDIT_NOTEBOOK,iMySQL_Front::OnEditNotebookPageChanged)

END_EVENT_TABLE()


void iMySQL_Front::OnAllowNotebookDnD(wxAuiNotebookEvent& evt)
{
    evt.Allow();
}

iMySQL_Front::iMySQL_Front()
{
}


void iMySQL_Front::OnDbMenuContextClick( wxCommandEvent& event ){
	int evt = event.GetId();
	//_OnTreeCtrlReloadActived(evt,editNotebook,treeview->GetSelection(),treeview,s_bar,currentDb,log,result);
}

void iMySQL_Front::OnMenuClick( wxCommandEvent& event ){
	int evt = event.GetId();
	if ( evt == ID_MENUITEM_FILE_EXIT){
		Destroy();
	}
	else if ( evt == ID_MENUITEM_BUILD_RUN_ALL || evt == ID_MENUITEM_BUILD_RUN_LINE ){
		OnTbClick(event);
	}
	/*switch(evt){
	case ID_MENUITEM_FILE_EXIT:
		Destroy();
		break;
	case ID_MENUITEM_BUILD_RUN_ALL:
		//wxMessageBox(wxT("aaa"));
		break;
	case ID_MENUITEM_VIEW_LOG:
		event.IsChecked() ? m_mgr.GetPane(wxT("Log")).Show() : m_mgr.GetPane(wxT("Log")).Hide();
		break;
	case ID_MENUITEM_VIEW_DB:
		event.IsChecked() ? m_mgr.GetPane(wxT("treeview")).Show() : m_mgr.GetPane(wxT("treeview")).Hide();
		break;
	case ID_MENUITEM_VIEW_AUTOCOMP:
		autocomp = !autocomp;
		break;
	case ID_MENUITEM_HELP_ABOUT:
		wxMessageBox(ABOUT,wxT("About"));
		break;
	case ID_MENUITEM_FILE_OPEN:
		OnFileOpen();
		break;
	case ID_MENUITEM_FILE_NEW:
		OnFileNew();
		break;
	case ID_MENUITEM_FILE_SAVE:
		OnFileSave();
		break;
	case ID_MENUITEM_BUILD_RUN_ALL:
		OnBuildRunAll();
		break;
	case ID_MENUITEM_BUILD_RUN_SELECTED:
		OnBuildRunSelected();
		break;
	case ID_MENUITEM_BUILD_RUN_LINE:
		OnBuildRunLine();
		break;
	case ID_MENUITEM_BUILD_RUN_TEXT:
	    _DoSQLQuery(editNotebook->GetCurrentMySQL(),editNotebook->GetCurrentLineText(),result,s_bar,currentDb,log,1);
		editNotebook->SetCurrentEditFocus();//->SetFocus();
		break;
	case ID_MENUITEM_TOOLS_EXPORT:
		OnToolsExportResult();
		break;
	case ID_MENUITEM_FILE_NEW_CONNECTION:
		_AddNewConnection(treeview,editNotebook,currentDb,s_bar);
		break;
	default:
		break;
	}*/
	ui->m_mgr.Update();
	//event.Skip();
}

iMySQL_Front::iMySQL_Front( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
    Create( parent, id, caption, pos, size, style );
}

iMySQL_Front::iMySQL_Front(/*wxMutex* mutex,
//							wxCondition* condition,*/
							wxWindow* parent, ServerInfo* serverInfo, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
    Create( parent, id, caption, pos, size, style );
	CreateControls(serverInfo);
	this->mutex = mutex;
}

bool iMySQL_Front::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
    wxFrame::Create( parent, id, caption, pos, size, style );

    SetIcon(wxIcon(mysql_xpm));
    Centre();

    return true;
}



iMySQL_Front::~iMySQL_Front()
{
	if ( ui )
		delete ui;
}

void iMySQL_Front::CreateControls(ServerInfo* serverInfo)
{   
	ui = new MyUI(this,serverInfo);
	try{
		BLL::AddDbListToTreeCtrl(ui,true,0);
	}
    catch ( ... ){
		wxMessageBox(wxT("Errno 1200"));
	}

}



bool iMySQL_Front::ShowToolTips()
{
    return true;
}

void iMySQL_Front::OnTbRunClick(wxCommandEvent &event)
{
	/*wxString query = editNotebook->GetCurrentSelectedText();
	query = (query == wxEmptyString) ? editNotebook->GetCurrentText() : query;
    _DoSQLQuery(editNotebook->GetCurrentMySQL(),query,result,s_bar,currentDb,log,0,mutex);
	editNotebook->SetCurrentEditFocus();*/
	event.Skip();
}

void iMySQL_Front::OnTreectrlActivated( wxTreeEvent& event )
{
	try{
		BLL::OnTreeCtrlActived(ui,event.GetItem());
	}
	catch (...) {
		wxMessageBox(wxT("Errorno 1201"));
	}
	event.Skip();
}


void iMySQL_Front::OnTbRunLineClick( wxCommandEvent& event )
{

	//result->Test();
	/*wxCriticalSectionLocker lock(*m_critsect);


	wxUIThread* thd = new wxUIThread(result,m_critsect,m_semAllDone);
	if ( thd->Create() != wxTHREAD_NO_ERROR){
		wxMessageBox(wxT("Thread Failed"));
	}
	thd->Run();
	//OnBuildRunLine();
	thd->Wait();*/
	OnBuildRunLine();
    event.Skip();
}


void iMySQL_Front::OnTbChangeFontEncodingClick( wxCommandEvent& event )
{
	/*if (charset)
		delete charset;
	switch(event.GetSelection()){
	case 0:
		charset = new wxCSConv(wxFONTENCODING_SYSTEM);
		break;
	case 1:
		charset = new wxCSConv(GBK);
		break;
	case 2:
		charset = new wxCSConv(wxFONTENCODING_UTF8);
		break;
	default:
		break;
	}*/
    event.Skip();
}

void iMySQL_Front::OnBeginDrag(wxTreeEvent &event)
{
	/*wxTreeItemId m_draggedItem = event.GetItem();
	wxPoint clientpt = event.GetPoint();
	wxPoint screenpt = ScreenToClient(clientpt);*/
	event.Allow();
}

void iMySQL_Front::OnEndDrag(wxTreeEvent &event)
{
	/*wxString value = treeview->GetItemText(event.GetItem());
	editNotebook->GetCurrentEdit()->AppendText(SPACE);
	editNotebook->GetCurrentEdit()->AppendText(value);*/
	event.Allow();
}

void iMySQL_Front::OnMouseRightClickTreeCtrl(wxTreeEvent &event)
{
	//MYSQL* mysql = _GetMySQLByTreeCtrlLayer(treeview->GetRootItem(),treeview,editNotebook);
	/*treeview->SelectItem(event.GetItem());
	DbContextMenu menu(treeview,event.GetItem());
    wxPoint clientpt = event.GetPoint();
	treeview->PopupMenu( &menu, clientpt.x, clientpt.y);
	event.Allow();*/
}

void iMySQL_Front::OnDbListChanged(wxCommandEvent &event)
{
	/*wxString db = event.GetString();
	_DoSQLQuery(editNotebook->GetCurrentMySQL(),wxT("use ")+db,result,s_bar,currentDb,log);
	event.Skip();*/
}

void iMySQL_Front::OnTbClick(wxCommandEvent &event)
{
	int evt = event.GetId();
	if ( evt ){
		try{
			BLL::DoSQLQuery(ui,evt);
		}
		catch(...){
			wxMessageBox(wxT("Errorno 1203"));
		}
	}
	/*if ( evt == ID_TB_NEW )
		OnFileNew();
	else if ( evt == ID_TB_SAVE )
		OnFileSave();
	else if ( evt == ID_TB_OPEN )
		OnFileOpen();
	else if ( evt == ID_TB_NEW_CONNECT )
		_AddNewConnection(treeview,editNotebook,currentDb,s_bar);
	else if ( evt == ID_TB_RUN )
		OnTbRunClick(event);
	else if ( evt == ID_TB_RUN_LINE )
		OnTbRunLineClick(event);
	else if ( evt == ID_TB_RUN_TEXT )
	    _DoSQLQuery(editNotebook->GetCurrentMySQL(),editNotebook->GetCurrentLineText(),result,s_bar,currentDb,log,1);
	else if ( evt == ID_TB_FONT_ENCODING )
		OnTbChangeFontEncodingClick(event);
	else if ( evt == ID_TB_CURRENT_DB )
		OnDbListChanged(event);
	editNotebook->SetCurrentEditFocus();*/
}


void iMySQL_Front::OnFileNew()
{
	/*if (editNotebook->GetCurrentEdit()->Modified()) {
	   if (wxMessageBox (_("Text is not saved, save before closing?"), _("Close"),
	                     wxYES_NO | wxICON_QUESTION) == wxYES) {
	       editNotebook->GetCurrentEdit()->SaveFile();
	       if (editNotebook->GetCurrentEdit()->Modified()) {
	            wxMessageBox (_("Text could not be saved!"), _("Close abort"),
	                          wxOK | wxICON_EXCLAMATION);
	             return;
	       }
	    }
	}
	editNotebook->GetCurrentEdit()->SetFilename (wxEmptyString);
	editNotebook->GetCurrentEdit()->ClearAll();
	editNotebook->GetCurrentEdit()->SetSavePoint();
	SetTitle(VERSION);*/
}

void iMySQL_Front::OnFileOpen()
{
/*#if wxUSE_FILEDLG
	wxString fname;
	wxFileDialog dlg (this, _T("Open file"), wxEmptyString, wxEmptyString, _T("Any file (*)|*"),
                     wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_CHANGE_DIR);
	if (dlg.ShowModal() != wxID_OK) return;
	fname = dlg.GetPath ();
	SetTitle(VERSION+fname);
	editNotebook->GetCurrentEdit()->LoadFile (fname);
#endif // wxUSE_FILEDLG*/
}

void iMySQL_Front::OnFileSave()
{
/*	if (!editNotebook->GetCurrentEdit()->Modified()) {
		wxMessageBox (_("There is nothing to save!"), _("Save file"),
                     wxOK | wxICON_EXCLAMATION);
		return;
	}
	editNotebook->GetCurrentEdit()->SaveFile();
	//SetTitle(VERSION+editor->GetFilename());*/
}

void iMySQL_Front::OnBuildRunAll()
{
/*	wxString query = editNotebook->GetCurrentEdit()->GetText();
    _DoSQLQuery(editNotebook->GetCurrentMySQL(),query,result,s_bar,currentDb,log);
	editNotebook->SetCurrentEditFocus();*/
}

void iMySQL_Front::OnBuildRunSelected()
{
/*	wxString query = editNotebook->GetCurrentSelectedText();//>GetCurrentEdit()->GetSelectedText();
    _DoSQLQuery(editNotebook->GetCurrentMySQL(),query,result,s_bar,currentDb,log);
	editNotebook->SetCurrentEditFocus();//->SetFocus();*/
}

void iMySQL_Front::OnBuildRunLine()
{
 /*   _DoSQLQuery(editNotebook->GetCurrentMySQL(),editNotebook->GetCurrentLineText(),result,s_bar,currentDb,log);
	editNotebook->SetCurrentEditFocus();//->SetFocus();*/
}

void iMySQL_Front::OnToolsExportResult()
{
 /*   wxString filename = wxEmptyString;
    wxFileDialog dlg (this, _T("Save file"), wxEmptyString, wxEmptyString, _T("Any file (*)|*"), wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
    if (dlg.ShowModal() != wxID_OK)
		return;
    filename = dlg.GetPath();
	_ExportResult(result,filename);*/
}


void iMySQL_Front::OnCloseButtonClick(wxCloseEvent &event)
{
	Hide();
	event.Veto();
}


void iMySQL_Front::OnEditNotebookPageChanged(wxAuiNotebookEvent &event)
{
	/*int old_index = event.GetOldSelection();
	int new_index = event.GetSelection();
	_OnPageChanged(old_index,new_index,editNotebook,currentDb,s_bar);*/
	/*int pos = event.GetSelection();
	int oldPos = event.GetOldSelection();
	wxString msg;
	msg.Printf(_("Old is %d, Now is %d"),oldPos,pos);
	wxMessageBox(msg);
	event.Veto();*/
}

void iMySQL_Front::OnLoadResult(wxCommandEvent& event)
{
	try{
		LoadEventData* data = (LoadEventData*)event.GetClientData();
		BLL::LoadingData(data->array,0,data->mysql,data->query,ui->editNotebook,ui->result,ui->s_bar,ui->currentDb,ui->log,data->type);
		delete data;
	}
	catch(...){
		wxMessageBox(wxT("Errorno: 1202"));
	}
}
